<template>
  <div v-if="isDesigner" class="pro-container" style="height: 300px">历史项目</div>
  <div v-else-if="mixEditable" class="pro-container" style="width: 280px">
    <div class="title">
      {{ finalTitle }}
      <div class="title_border"></div>
    </div>
    <div class="content">
      <el-button type="primary" @click="autoAllComp(true, checkedCol)" size="mini">填充选中</el-button>
      <el-button type="primary" @click="autoAllComp(false, checkedCol)" size="mini">撤销选中</el-button>
      <div class="content_main" :style="{ 'max-height': 'calc(100vh - 260px)', height: contentHeight || 'calc(100vh - 300px)' }">
        <div v-for="(project, pIndex) in projects" :key="index" @click="clickPro(pIndex)" class="content_item">
          <div v-if="currentIndex === pIndex" class="is_current">
            <i class="el-icon-check"></i>
          </div>
          <div class="p_title" style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" :title="Fields[0] ? getDeepValue(Fields[0], project) : (project.title || project.name)">{{ Fields[0] ? getDeepValue(Fields[0], project) : (project.title || project.name) }}</div>
          <div class="p_des">
            <span style="flex: 1">
              <span v-if="project.createdTime || project.createTime">
                {{ (project[Fields[1]] || project.createdTime || project.createTime || '').split(' ')[0] }}
              </span>
              <span v-if="project[Fields[2]]"> ~ </span>
              <span v-if="project[Fields[2]]">
                {{ (project[Fields[2]]).split(' ')[0] }}
              </span>
            </span>
            <span style="font-size: 13px; padding-right: 8px" v-if="currentIndex === pIndex">展开</span>
            <el-button type="text" @click="openView(project)" style="font-size: 13px">查看</el-button>
          </div>
          <div v-if="currentIndex === pIndex" class="p_content">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" class="mb-5">
              <span>全选</span>
              <el-button type="text" class="fr" @click="autoAllComp(false)">撤销 </el-button>
              <el-button type="text" class="fr" @click="autoAllComp(true)"> 填充</el-button>
            </el-checkbox>
                  
            <el-checkbox-group v-model="checkedCol" @change="handleCheckedColChange">
                <el-checkbox v-for="(col, cIndex) in colums" :key="cIndex" :label="cIndex" class="mb-5">
                  <span>{{col.label}}</span>
                  <el-button type="text" class="fr" @click="autoComp(col, pIndex, false, false)">撤销 </el-button>
                  <el-button type="text" class="fr" @click="autoComp(col, pIndex)"> 填充</el-button>
                </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { findComponentUpward } from '@/utils/util.js'
import { AjaxUtil } from 'base/lib'
import { cloneDeep, sortBy, groupBy, forEach, isArray, get } from 'lodash'
import { loadRoute3Path, createIframe, openIframe } from '@/utils/loadRemote'

export default {
  name: 'historyProject',
  props: {
    value: null,
    mode: {
      default: 'edit' // 编辑模式和 edit， 展示模式 view
    },
    proTitle: {
      type: String,
      default: ''
    },
    contentHeight: {
      default: ''
    },
    colTitle: {
      type: String,
      default: ''
    },
    colums: {},
    layout_id: {},
    layout_id_left: {},
    // 查询条件
    condition: {},
    colTitleField: {},
    // 子表格主外键带入去除，默认id,projectId
    noAddField: {
      type: String,
      default: 'id,projectId,projectTypeId,projectTypeName,submitTime,processState,processDefId,processInstId,watermarkNo,acceptNo,year,manageUnitId,manageUnitName,manageUnitType,createdId,createdTime,createdName,createdOrgName,createdOrgCode,updatedId,updatedName,updatedTime,updatedOrgName,updatedOrgCode,deleteState,acceptTime,projectState,responsibilityId,responsibilityName,projectOpinion,fundingAmount,firstYearFunding,secondYearFunding,thirdYearFunding,approvalOpinion,projectBatch,projectNumber,projectApprovalNumber,fundingMethod,fundingDocumentNumber,finalProjectOpinion,projectFlowState,planType,manageUnitOffice,manageUnitOfficeName,responsibilityOffice,responsibilityOfficeName,projectComparisonResult,dishonestComparisonResult,applyAmount,summaryPersonId,summaryPerson,summaryTime,projectYear,projectAmount,changeType,changeStatus,changeTime,contractExpirationDate,paperMaterialReceived,applicationProcessingTime,financialAcceptanceStatus,acceptanceForm,acceptanceExpertOpinionStatus,processingTime,certificateHandleTime,certificateHandleStatus,reportCode,reportName,reportType,modifyStatus,changeCode,certificateProcessingTime,notificationSituation,certificationProcessingStatus,reportProcessState,reportPlanId,resourceCode,bdlx,pdfFile,wordFileId,pdfFileId,historyState,acceptNoticeStatus,projectTypeFullName,centralizId,centralizName,planId,lastExportpdfDate,dishonestPassReason,projectPassReason,registerRecordPdf,registerNumber,zwptProjid,govItemCode,govItemName,batch,prpXml,formSource,isGovType'
    }
  },
  data() {
    return {
      currentIndex: 0,
      projects: [],
      checkAll: false,
      isIndeterminate: false,
      checkedCol: [],
      initFormData: {}
    }
  },
  computed: {
    isDesigner() {
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === 'edit'
    },
    finalTitle() {
      if (this.proTitle) {
        return this.proTitle
      } else {
        return findComponentUpward(this).displayName || '历史项目'
      }
    },
    resourceCode() {
      return findComponentUpward(this).formCode
    },
    entityName() {
      return findComponentUpward(this).entityName
    },
    // 字段处理
    Fields() {
      let val = ''
      if (this.colTitleField && this.colTitleField.indexOf('+') !== -1) {
        val = this.colTitleField.split('+')
      } else {
        val = [this.colTitleField || '', '', '']
      }
      return val
    },
    // 默认不带入字段，及主外键
    noAddFieldList () {
      return this.noAddField ? this.noAddField.split(',') : []
    }
  },
  watch: {
    mixEditable: {
      immediate: true,
      handler(val) {
        console.log(val, '====')
        if (this.layout_id) {
          // 添加隐藏样式
          this.$nextTick(() => {
            const container = findComponentUpward(this).$refs[this.layout_id]
            if (!val && container) {
              if (!container.style) {
                this.$set(container, 'style', '{display:none;}')
              } else {
                this.$set(container.style, 'display', 'none')
              }
            }
          })
        }
      }
    }
  },
  async mounted() {
    this.searchData()
    const preUrl = loadRoute3Path('')
    const formIndexPage = `${preUrl}/index.html#/module/formDesigner/page/render`
    createIframe(formIndexPage)
    setTimeout(()=> {
      const data = findComponentUpward(this)
      this.initFormData = cloneDeep(data.formData)
      console.log(this.initFormData,'===this.initFormData')
    }, 2000)
  },
  methods: {
    handleCheckedColChange(val) {
      console.log(val,'===11')
      if (this.checkedCol.length === this.colums.length) {
        this.checkAll = true
      } else if (this.checkedCol.length === 0) {
        this.checkAll = false
        this.isIndeterminate = false
      } else {
        this.isIndeterminate = true
      }
    },
    handleCheckAllChange(val) {
      console.log(val,'===val')
      let checkedCol = []
      if (val) {
        this.colums.forEach((c, cIndex) => checkedCol.push(cIndex))
      }
      this.checkedCol = checkedCol
      console.log(this.checkedCol,'===this.checkedCol')
    },
    getDeepValue(str, value) {
      const arr = str.split('.')
      return arr.reduce(function (acc, key) { return acc &&  key in acc ? acc[key] : null; }, value)
    },
    clickPro(pIndex) {
      this.currentIndex = pIndex
    },
    async searchData() {
      //   console.log(findComponentUpward(this),'==findComponentUpward(this)')
      // console.log(this.colums,'===colums.formData')
      const entityName = findComponentUpward(this).entityName
      const { data } = await AjaxUtil.ajax({
        url: `/api/lowcode/models/actions/query-with-page?entityName=${entityName}&pageIndex=0&pageSize=9999&cascadeDeep=-1`,
        method: 'POST',
        data: this.condition || {}
      })
      console.log(data, '===data')
      this.projects = data.data
      // this.$emit('autoComplete', this.projects[this.currentIndex])
    },
    async queryFormResource() {},
    async querySdoTypes() {
      //
      const resp = await AjaxUtil.ajax({
        url: `/api/lowcode/runtimes/sdo-types`,
        method: 'GET',
        data: {}
      })
      return resp.data
    },
    // 对象是否有值
    isExitObj(object) {
      if (!object) {
        return false
      }
      let isExit = false
      Object.keys(object).forEach(el => {
        // 排除值为对象---iframe
        if (object[el] !== null && object[el] !== '' && object[el] !== undefined && typeof object[el] !== 'object') {
          console.log(object[el], el, '==el')
          isExit = true
        }
      })
      return isExit
    },
    autoComp(col, pIndex, confirm = true, isComp = true) {
      console.log(isComp,'===isComp')
      let projectObj = null
      if (!isComp) {
        projectObj = cloneDeep(this.initFormData)
      } else {
        projectObj = cloneDeep(this.projects[pIndex])
      }
      // console.log(projectObj,'===projectObj')
      // 先判断是否存在数据
      const isExit = col.children.some(c => {
        // console.log(c.tag === 'frame' && this.isExitObj(findComponentUpward(this).formData[c.__vModel__]),'==frame')
        // console.log(!['frame', 'children'].includes(c.tag) && findComponentUpward(this).formData[c.__vModel__],'====input')
        let exit =
          (c.tag === 'frame' && this.isExitObj(findComponentUpward(this).formData[c.__vModel__])) ||
          (c.tag === 'children' && isArray(findComponentUpward(this).formData[c.__vModel__]) && findComponentUpward(this).formData[c.__vModel__].length > 0) ||
          (!['frame', 'children'].includes(c.tag) && findComponentUpward(this).formData[c.__vModel__])
        return exit
      })
      const pageThis = findComponentUpward(this)
      // console.log('===pageThis',pageThis)
      const autoChildren = (that, key) => {
        // 子表格填充
        const { f_disabled, f_readonly, f_visible } = that
        // const key = c.__vModel__
        // (f_visible[key]) &&
        const isEdit = !f_disabled[key] && !f_readonly[key]
        // console.log(isEdit,'===isEdit')
        const exitItem = that.$refs['ref_' + key] !== undefined
        if (isEdit) {
          const that = findComponentUpward(this)
          that.Api.getFrameAsync(key)
            .then(el => {
              console.log(key,'====test')
              console.log(Object.keys(el.validRules), '====childrenel.validRules')
              // Object.keys(el.validRules) 展示的字段
              const list = projectObj[key].map(i => {
                let obj = {
                  ...i,
                  "__operate_type": "add"
                }
                this.noAddFieldList.forEach(j => {
                  delete obj[j]
                })
                return obj
              })
              console.log(list, '====list')
              const initList = that.formData[key].map(i => {
                return {
                  ...i,
                  "__operate_type": "delete"
                }
              })
              this.$set(that.formData, key, initList.concat(list))
              if ((that.formData, '__' + key + 'Object')) {
                this.$set(that.formData, '__' + key + 'Object', projectObj['__' + key + 'Object'])
              }
            })
            .catch(error =>  {
              console.log(key,'未获取到iframe1')
              console.log(error, '====未获取到iframe2')
            })
        }
      }
      const autoOther = (that, key) => {
        const { f_disabled, f_readonly, f_visible } = that
        // const key = c.__vModel__
        // (f_visible[key]) &&
        const isEdit = !f_disabled[key] && !f_readonly[key]
        // console.log(isEdit,'===isEdit')
        const exitItem = that.$refs['ref_' + key] !== undefined
        if (isEdit) {
          // const that = findComponentUpward(this)
          this.$set(that.formData, key, projectObj[key])
          if ((that.formData, '__' + key + 'Object')) {
            this.$set(that.formData, '__' + key + 'Object', projectObj['__' + key + 'Object'])
          }
        }
      }
      const auto = (isInfo = false) => {
        const isExit = col.children.some(c => c.__vModel__ && (c.__vModel__.indexOf('.') !== -1) && !!pageThis.formData[c.__vModel__.split('.')[0]][c.__vModel__.split('.')[1]])
        const add = () => {
          col.children.forEach(c => {
            console.log(c,'====c',projectObj)
            console.log(this.noAddFieldList.includes(c.__vModel__),c.__vModel__,'===排除的字段')
            // 填充数据
            if (projectObj && projectObj[c.__vModel__]) {
              console.log(c.__vModel__, c.tag, '====c.tag')
              if (c.tag === 'frame') {
                const iframeAuto = (that, item, temp) => {
                  const field = item.__vModel__ || temp.slice(temp.lastIndexOf('.') + 1)
                  // console.log(field,'field')
                  that.Api.getFrameAsync(field)
                    .then(el => {
                      // console.log('===then')
                      console.log(!(el.$refs && el.$refs.xTable),'表格')
                      if (!(el.$refs && el.$refs.xTable)) {
                        const { f_disabled, f_readonly, f_visible } = el
                        let data = projectObj
                        for (let t of (item.__vModel__ || temp).split('.')) {
                          data = data[t]
                        }
                        // console.log(data,'=========================data')
                        for (let key in data) {
                          console.log(this.noAddFieldList,'this.noAddFieldList')
                          if (data.hasOwnProperty(key) && !this.noAddFieldList.includes(key)) {
                            // (f_visible[key]) &&
                            const isEdit = !f_disabled[key] && !f_readonly[key]
                            // console.log(isEdit,'===isEdit')
                            // 隐藏组件和没绑定组件
                            const exitItem = el.$refs['ref_' + key] !== undefined
                            console.log(exitItem,'===el.$refs[')
                            // console.log(key,f_visible[key],exitItem,exitItem && f_visible[key] || !exitItem && !f_visible[key],'key,visiable,exit,====f_visible[key]')
                            // console.log(exitItem && el.$refs['ref_'+ key]['$vnode'].tag.endsWith('pm-frame') ,isEdit,'====可填充',key)
                            // 判断资源容器中的组件是否也是资源容器
                            if (exitItem && el.$refs['ref_' + key]['$vnode'].tag.endsWith('pm-frame')) {
                              console.log(data[key], '===data[key]')
                              if (data[key]) {
                                console.log(el, {}, field + '.' + key)
                                iframeAuto(el, {}, field + '.' + key)
                              }
                              // 组件存在且未隐藏 || 组件隐藏 !exitItem && !f_visible[key]
                            } else if (isEdit) {
                              // 1:1
                              // debugger
                              const arr = (item.__vModel__ || temp).split('.')
                              let keys = arr || []
                              let __keysObject = (item.__vModel__ || temp).split('.') || []
                              __keysObject.push('__' + key + 'Object')
                              keys.push(key)
                              let setDeepValue = (object, path, value, container) => {
                              console.log( path, value, container,'===container')
                                if (container) {
                                  container.Api.getFrameAsync(path[0]).then(c => {
                                    if (path.length == 2) {
                                      c.formData[path[1]] = value
                                    } else if (path.length > 2) {
                                      setDeepValue(object[path[0]], path.slice(1), value, c)
                                    }
                                  })
                                } else {
                                    let fieldPath = [...path]
                                    if (fieldPath.length) {
                                      const keyItem = fieldPath.shift()
                                      if (object) {
                                        this.$set(object, keyItem, setDeepValue(object[keyItem], fieldPath, value))
                                      }
                                    } else {

                                      object = value
                                    }
                                    return object
                                  }
                              }
                              // var abc = {a:{b:{c:{d:{e:{f:123}}}}}}
                              // setDeepValue(abc,['a','b','c','d','e','f'],456)
                              let cData = cloneDeep(data[key])
                              if (isArray(cData)) {
                                // 1:1:n
                                // el.Api.getFrameAsync(key)
                                  // .then(cEl => {
                                  const list = data[key].map(i => {
                                    let obj = {
                                      ...i,
                                      "__operate_type": "add"
                                    }
                                    this.noAddFieldList.forEach(j => delete obj[j])
                                    return obj
                                  })
                                  const initList = that.formData[key].map(i => {
                                    return {
                                      ...i,
                                      "__operate_type": "delete"
                                    }
                                  })
                                setDeepValue(findComponentUpward(this).formData, keys, initList.concat(list), null)
                              // })
                              } else {
                                setDeepValue(findComponentUpward(this).formData, keys, cData,findComponentUpward(this))
                                setDeepValue(findComponentUpward(this).formData, __keysObject, data['__' + key + 'Object'], findComponentUpward(this))
                              }
                              
                            }
                          }
                        }
                      } else {
                        // 子表格
                        const that = findComponentUpward(this)
                        console.log(projectObj[field], '=====projectObj[field]')
                        this.$set(that.formData, field, projectObj[field])
                        if ((that.formData, '__' + field + 'Object')) {
                          this.$set(that.formData, '__' + field + 'Object', projectObj['__' + field + 'Object'])
                        }
                      }
                    })
                    .catch(error => console.log(error, '====未获取到iframe'))
                }
                iframeAuto(pageThis, c)
              } else if (c.tag === 'children') {
                // 1:n
                autoChildren(pageThis, c.__vModel__)
              } else if(!this.noAddFieldList.includes(c.__vModel__)) {
                autoOther(pageThis, c.__vModel__)
              }
            } else if (c.__vModel__ && (c.__vModel__.indexOf('.') !== -1)) {
              // 单独处理1:1的字段拿到主表使用
              const path = c.__vModel__.split('.')
              if (projectObj[path[0]] || projectObj[path[0]][path[1]] === null) {
                this.$set(pageThis.formData[path[0]], path[1], projectObj[path[0]][path[1]])
              }
              if ((pageThis.formData[path[0]], '__' + path[1] + 'Object')) {
                this.$set(pageThis.formData[path[0]], '__' + path[1] + 'Object', projectObj[path[0]]['__' + path[1] + 'Object'])
              }
            } else if (c.__vModel__ && !this.noAddFieldList.includes(c.__vModel__)) {
              autoOther(pageThis, c.__vModel__)
              // console.log('没有字段' + c.__vModel__)
            }
          })
        }
        if (!isInfo && isExit && confirm) {
          this.$confirm(`${col.label}可能已输入内容，填充将会覆盖原内容，是否继续？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              add()
            })
            .catch(() => {
              return
            })
        } else {
          add()
        }
      }
      if (isExit && confirm && isComp) {
        this.$confirm(`${col.label}可能已输入内容，填充将会覆盖原内容，是否继续？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            auto(true)
          })
          .catch(() => {})
      } else {
        auto()
      }
    },
    autoAllComp(isComp, selections = this.colums.map((i, index) => index)) {
    // fi_字段---formitem
    console.log(selections,'===selections')
      if(selections.length === 0) {
        this.$message.warning('请先选中数据！')
        return
      }
      this.$confirm(`此操作将${isComp ? '填充并覆盖' : '重置'}${selections.length === this.colums.length ? '所有' : '选中'}数据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      })
        .then(() => {
          this.colums.forEach((c, cIndex) => {
            if (selections.includes(cIndex)) {
              try {
                this.autoComp(c, this.currentIndex, false, isComp)
              }
              catch(err) {
                console.log("填入报错", err.message)
              }
            }
          })
          // 第一层的数据除了主外键，都赋一遍值
          this.complete(isComp)
        })
        .catch(() => {})
    },
    // 一键带入时， 第一层的数据除了主外键，都赋一遍值
    complete(isComp) {
      let projectObj = null
      if (!isComp) {
        projectObj = cloneDeep(this.initFormData)
      } else {
        projectObj = cloneDeep(this.projects[this.currentIndex])
      }
      // 第一层数据处理，除对象，数组，主外键，都带入
      const list = this.noAddField.split(',')
      list.forEach(i => {
          console.log(i,'====i')
          console.log(projectObj[i],'====projectObj[i]')
          i && delete projectObj[i]
      })
      console.log(projectObj,'==projectObj')
      const pageThis = findComponentUpward(this)
      for (let key in projectObj) {
        if (projectObj.hasOwnProperty(key)) {
          // Object.prototype.toString.call(val) === '[object Array]' // true 代表为数组
          // Object.prototype.toString.call(val) === '[object Object]' // true 代表为对象
          if (Object.prototype.toString.call(projectObj[key]) !== '[object Array]' && Object.prototype.toString.call(projectObj[key]) !== '[object Object]'){
            console.log(key, projectObj[key],'===projectObj[key]')
            this.$set(pageThis.formData, key, projectObj[key])
          }
        }
      }
      console.log(pageThis.formData, '========pageThis.formData')
    },
    openView(project) {
      const { formCode, displayName, $attrs, pkField } = findComponentUpward(this)
      const mode = get($attrs, 'mode', null)
      console.log(findComponentUpward(this))
      // const {formCode, pkField } = findComponentUpward(this)
      // findComponentUpward(this).Api.openDialog({
      //   "id": formCode,
      //   "resourceType": 'form',
      //   "dialog": {
      //     "isCheckChange": 'false',
      //     "title": `查看${this.finalTitle}`,
      //     "width": '960px',
      //     "top": '15vh',
      //     "modal": false,
      //     "mode": 'dialog',
      //     "center": false,
      //   },
      //   "props": {
      //     "status": 'view',
      //     initFormData: project,
      //     pkId: pkField,
      //     editable: false
      //   }
      // })
      const preUrl = loadRoute3Path('')
      const url = `${preUrl}/index.html#/module/formDesigner/page/render?resourceType=form&resourceCode=${formCode}&appName=EOSLOWCODE&displayName=${displayName}&status=view&ID=${project[pkField]}`
      // window.open(url, '_blank')
      openIframe(url)
    }
  }
}
</script>

<style lang="scss" scoped>
.pro-container {
  width: 280px;
  border-left: 1px solid #e5e5e5;
  margin-left: -5px;
  position: fixed;
  // height: 'calc(100vh - 230px)';
  .title {
    padding-left: 10px;
    display: inline-block;
    color: var(--tagBg);
    font-size: 16px;
    font-weight: 700;
    .title_border {
      margin: 0px auto 3px;
      height: 4px;
      width: 45px;
      border-radius: 6px;
      background-color: var(--tagBg);
    }
  }
  .content {
    padding: 15px 10px 0 10px;
    border-top: 1px solid #e5e5e5;
    // margin-left: -5px;
    margin-right: -5px;
    height: 100%;
    .content_main {
      overflow: auto;
    }
    .content_item {
      background-color: #f2f2f2;
      margin-top: 10px;
      padding: 8px;
      // position: absolute;
      // right: 12px;
      // display: flex;
      .P_title {
        font-weight: 700;
        line-height: 20px;
      }
      .p_des {
        display: flex;
      }
      .is_current {
        width: 0;
        height: 0;
        border-width: 0 35px 35px 0;
        border-style: solid;
        border-color: transparent #4ba435 transparent transparent;
        margin-top: -8px;
        margin-right: -8px;
        float: right;
        .el-icon-check {
          color: #fff;
          padding-left: 19px;
        }
      }
      .p_content {
        padding: 5px;
        .el-checkbox {
          margin-right: 0;
        }
        label.el-checkbox {
          display: flex;
          .el-checkbox__input.is-checked + .el-checkbox__label {
            color: #000;
          }
          ::v-deep .el-checkbox__label {
            width: 100%;
            display: block;
            line-height: 16px;
            font-size: 15px;
            flex: 1;
            button {
              padding-top: 0 !important;
              padding-left: 5px !important;
            }
          }
        }
        .item {
          display: flex;
          .item_circle {
            width: 12px;
            height: 12px;
            margin: 8px 8px 0 0;
            border-radius: 6px;
            background-color: var(--tagBg);
          }
          .item_content {
            flex: 1;
          }
        }
      }
    }
    .p_des {
      font-size: 12px;
      color: #999;
    }
  }
}
</style>
